<template>
  <div id="Users">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索-->
        <el-col :span="8">
          <el-input v-model="QueryInfor.query" placeholder="请输入内容" clearable size="small" @clear="GetUserListData">
            <el-button slot="append" icon="el-icon-search" @click="GetUserListData" />
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="4">
          <el-button type="primary" size="small" @click="AddUserClick">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table
        :data="UsersLisData"
        border
        stripe
        size="small"
        style="width: 100%"
        :highlight-current-row="true"
      >
        <el-table-column label="#" type="index" width="50" align="center" />
        <el-table-column label="姓名" prop="username" align="center" />
        <el-table-column label="邮箱" prop="email" align="center" />
        <el-table-column label="电话" prop="mobile" align="center" />
        <el-table-column label="角色" prop="role_name" align="center" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="禁用"
              @change="TableSwitch(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="EditData(scope.row)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="DeleteData(scope.row, scope.$index)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="分配用户" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="ToolsData(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :current-page="QueryInfor.pagenum"
        :page-sizes="[10, 15, 20, 25, 30, 35, 40]"
        :page-size="QueryInfor.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 弹窗区域 -->
    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="AddUserDialog"
      width="50%"
      :close-on-click-modal="false"
      @close="AddUserDialogClose"
    >
      <el-form
        ref="AddFormRef"
        :model="AddForm"
        :rules="AddFormRules"
        label-width="100px"
        class="demo-ruleForm"
        size="small"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="AddForm.username" maxlength="10" minlength="3" placeholder="请输入用户名称" clearable />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="AddForm.password" maxlength="15" minlength="6" type="password" placeholder="请输入密码" clearable />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="AddForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="AddForm.mobile" maxlength="11" placeholder="请输入手机号" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="AddUserDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="AddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户END -->

    <!-- 编辑用户 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="EidtUserDialog"
      width="50%"
      :close-on-click-modal="false"
      @close="EidtUserDialogClose"
    >
      <el-form
        ref="EidtFormRef"
        :model="EidtForm"
        :rules="EidtFormRules"
        label-width="100px"
        class="demo-ruleForm"
        size="small"
      >
        <el-form-item label="用户名称">
          <el-input v-model="EidtForm.username" disabled maxlength="10" minlength="3" placeholder="请输入用户名称" clearable />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="EidtForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="EidtForm.mobile" maxlength="11" placeholder="请输入手机号" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="EidtUserDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="EidtUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户END -->

    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="ToolsDialog"
      width="50%"
      :close-on-click-modal="false"
      @close="ToolsDialogClose"
    >
      <el-form
        :model="ToolsForm"
        label-width="100px"
        class="demo-ruleForm"
        size="small"
      >
        <el-form-item label="当前用户">
          <el-input v-model="userinfo.username" disabled maxlength="10" minlength="3" placeholder="请输入用户名称" clearable />
        </el-form-item>

        <el-form-item label="当前角色">
          <el-input v-model="userinfo.role_name" disabled placeholder="请输入邮箱" clearable />
        </el-form-item>

        <el-form-item label="分配新角色">
          <el-select v-model="ToolsForm.roleId" clearable filterable placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in UserRoleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
              filterable
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="ToolsDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="ToolsDialogOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限END -->
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱
    const checkEmal = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      } else {
        const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的邮箱'))
        }
      }
    }
    // 验证手机号
    const checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      // 数据参数
      QueryInfor: {
        query: '', // 查询参数
        pagenum: 1, // 当前页
        pagesize: 10 // 每页显示条数
      },
      UsersLisData: [], // 列表数据
      total: 0,
      AddUserDialog: false, // 添加弹窗
      AddForm: {
        username: '', // 用户名称
        password: '', // 密码
        email: '', // 邮箱
        mobile: '' // 手机号
      },
      EidtUserDialog: false, // 编辑弹窗
      EidtForm: {
        id: '', // id
        username: '', // 用户名称
        email: '', // 邮箱
        mobile: '' // 手机号
      },
      // 添加用户验证
      AddFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名称的长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在 6 到 15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: checkEmal, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: checkMobile, trigger: 'blur' }
        ]
      },
      ToolsDialog: false, // 控制分配角色对话框
      // 编辑用户验证
      EidtFormRules: {
        email: [
          { required: true, validator: checkEmal, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: checkMobile, trigger: 'blur' }
        ]
      },
      userinfo: {}, // 用户信息
      UserRoleList: [], // 角色分配下拉框列表
      ToolsForm: {
        roleId: '' // 以选中的新角色id
      }
    }
  },
  /* HTML DOM加载后马上执行的，如赋值*/
  computed: {},

  /* 观察Vue实例上的数据变动 */
  watch: {},

  /* 模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图 */
  created() {
    this.GetUserListData()
  },

  /* 模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作 */
  mounted() {},

  /* methods则必须要有一定的触发条件才能执行 */
  methods: {
    // 获取列表数据1.3.1
    async GetUserListData() {
      const { data: resData } = await this.$http.get('users', { params: this.QueryInfor })
      if (resData.meta.status !== 200) {
        this.$message.error(resData.meta.msg)
      } else {
        console.log('获取列表数据', resData)
        this.UsersLisData = resData.data.users
        this.total = resData.data.total
      }
    },
    // 添加用户
    AddUserClick() {
      console.log('添加用户')
      this.AddUserDialog = true
    },
    // 监听对话框关闭事件
    AddUserDialogClose() {
      this.$refs.AddFormRef.resetFields()
    },
    // 监听编辑对话框关闭
    EidtUserDialogClose() {
      this.$refs.EidtFormRef.resetFields()
    },
    // 添加确定1.3.2
    AddUser() {
      this.$refs.AddFormRef.validate(async valid => {
        if (valid) {
          const { data: resData } = await this.$http.post('users', { params: this.AddForm })
          if (resData.meta.status !== 201) {
            this.$message.error(resData.meta.msg)
          } else {
            this.$message.success(resData.meta.msg)
            this.AddUserDialog = false
            this.GetUserListData()
          }
        } else {
          return false
        }
      })
    },
    // 编辑1.3.4
    async EditData(EditData) {
      console.log('编辑弹窗', EditData)
      const { data: resData } = await this.$http.get('users/' + EditData.id, { params: this.EidtForm })
      console.log('根据 ID 查询用户信息', resData)
      if (resData.meta.status !== 200) {
        this.$message.error(resData.meta.msg)
      } else {
        this.EidtForm = resData.data
      }
      this.EidtUserDialog = true
    },
    // 编辑确定1.3.5
    EidtUser() {
      this.$refs.EidtFormRef.validate(async valid => {
        if (valid) {
          const { data: resData } = await this.$http.put('users/' + this.EidtForm.id, {
            email: this.EidtForm.email,
            mobile: this.EidtForm.mobile
          })
          if (resData.meta.status !== 200) {
            this.$message.error(resData.meta.msg)
          } else {
            this.$message.success(resData.meta.msg)
            this.EidtUserDialog = false
            this.GetUserListData()
          }
        } else {
          return false
        }
      })
    },
    // 删除1.3.6
    async DeleteData(DeleteData, index) {
      console.log('删除', DeleteData, index)
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 数据保护机制（前两条无法删除，利用index>=1[从0开始]来判断）
      if (index > 1) {
        // 如果用户点击确定（确定删除） 返回confirm 否则(取消删除)返回cancel
        if (confirmResult === 'confirm') {
          const { data: resData } = await this.$http.delete('users/' + DeleteData.id)
          if (resData.meta.status !== 200) {
            this.$message.error(resData.meta.msg)
          } else {
            this.$message.success(resData.meta.msg)
            this.GetUserListData()
          }
        } else {
          return this.$message.error('用户已取消删除')
        }
      } else {
        return this.$message.error('触发数据保护，表格前两条无法删除')
      }
    },
    // 分配用户
    async ToolsData(ToolsData) {
      console.log('分配用户', ToolsData)
      this.userinfo = ToolsData
      // 获取所有角色列表
      const { data: resData } = await this.$http.get('roles')
      if (resData.meta.status !== 200) {
        this.$message.error(resData.meta.msg)
      } else {
        this.UserRoleList = resData.data
      }
      this.ToolsDialog = true
    },
    // 角色分配确定
    async ToolsDialogOk() {
      console.log('角色分配确定')
      if (!this.ToolsForm.roleId) {
        return this.$message.error('请分配新角色')
      } else {
        const { data: resData } = await this.$http.put('users/' + this.userinfo.id + '/role', {
          rid: this.ToolsForm.roleId
        })
        if (resData.meta.status !== 200) {
          this.$message.error(resData.meta.msg)
        } else {
          this.$message.success('分配成功')
          this.ToolsDialog = false
          this.GetUserListData()
        }
      }
    },
    // 监听分配角色弹窗
    ToolsDialogClose() {
      this.userinfo = {} // 用户信息
      this.ToolsForm.roleId = ''
    },
    // 状态切换1.3.3
    async TableSwitch(TableSwitch) {
      console.log('TableSwitch', TableSwitch)
      const { data: resData } = await this.$http.put(`users/${TableSwitch.id}/state/${TableSwitch.mg_state}`)
      if (resData.meta.status !== 200) {
        TableSwitch.mg_state = !TableSwitch.mg_state
        this.$message.error(resData.meta.msg)
      } else {
        this.$message.success(resData.meta.msg)
        this.GetUserListData()
      }
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      console.log('监听pagesize改变事件', newSize)
      this.QueryInfor.pagesize = newSize
      this.GetUserListData()
    },
    // 监听页码页改变值
    handleCurrentChange(newCurrent) {
      console.log('监听页码页改变值', newCurrent)
      this.QueryInfor.pagenum = newCurrent
      this.GetUserListData()
    }
  }
}
</script>

<style style lang='scss' scoped>

</style>
